package oop.analyzer.method;

import oop.analyzer.AnalyzerMethod;
import oop.data.DataStore;
import oop.data.RowData;

import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 根据日期排序
 */
public class SortMethod implements AnalyzerMethod{

    @Override
    public DataStore execute(DataStore dataStore) {
        final List<RowData> datas = dataStore.getDatas();


        //排序,有小于1970的时间，正则比较年月日

        datas.sort(new Comparator<RowData>() {
            @Override
            public int compare(RowData o1, RowData o2) {
                String date1  = o1.getValue("Date").replaceAll("-","/");
                String date2  = o2.getValue("Date").replaceAll("-","/");


                int y1=0,y2=0,m1=0,m2=0,d1=0,d2=0;

                Pattern pattern1 = Pattern.compile("(\\d+)/(\\d+)/(\\d+)");
                Matcher matcher1 = pattern1.matcher(date1);
                while(matcher1.find()){
                    y1 =  Integer.parseInt(matcher1.group(1));
                    m1 = Integer.parseInt(matcher1.group(2));
                    d1 = Integer.parseInt(matcher1.group(3));
                }
                Matcher matcher2 = pattern1.matcher(date2);
                while(matcher2.find()){
                    y2 =  Integer.parseInt(matcher2.group(1));
                    m2 = Integer.parseInt(matcher2.group(2));
                    d2 = Integer.parseInt(matcher2.group(3));
                }
                //统一日期格式
                date1 = Integer.toString(y1) + "/" + Integer.toString(m1) + "/" + Integer.toString(d1);
                date2 =  Integer.toString(y2) + "/" + Integer.toString(m2) + "/" + Integer.toString(d2);
                o1.setDatas("Date",date1);
                o2.setDatas("Date",date2);
                return (y1 != y2)?(y1 - y2):(m1 != m2)?(m1 - m2):(d1 != d2)?(d1 - d2): -1;

            }
        });

        return dataStore;
    }

}
